package com.qrxl.common.controller;

import com.qrxl.common.GlobalExceptionHandler;
import com.qrxl.common.JGConstant;
import com.qrxl.common.exception.CustomException;
import com.qrxl.enums.EnumUserType;
import com.qrxl.enums.HjReturnCode;
import com.qrxl.user.vo.UserLoginInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * 基类action,常用方法写在这里
 *
 * @author friday
 */
public abstract class BaseController extends GlobalExceptionHandler {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * 取得当前会话的request
     *
     * @return
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest();
        return request;
    }

    /**
     * 取得当前会话的response
     *
     * @return
     */
    public HttpServletResponse getResponse() {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getResponse();
        return response;
    }

    /**
     * 获取Session
     *
     * @return
     */
    public HttpSession getSession() {
        return getRequest().getSession();
    }

    /**
     *
     * @return
     * @author zhoukun
     */
    public UserLoginInfo getUserLoginInfo() {
        UserLoginInfo userLoginInfo = (UserLoginInfo) getSession().getAttribute(JGConstant.USER_SESSION_KEY);
        if (userLoginInfo == null) {
            throw new CustomException(HjReturnCode.NO_LOGIN_ERROR);
        }
        return userLoginInfo;
    }

    /**
     * entity列表转换为指定VO
     * @param clazz
     * @param records
     * @param <T>
     * @return
     */
    public <T> List<T> entityList2VO(Class<T> clazz, List records) {
        if (records == null) {
            return null;
        }
        ArrayList<T> arrayList = new ArrayList<>(records.size());
        records.forEach(bo -> {
            try {
                T vo = clazz.newInstance();
                BeanUtils.copyProperties(bo, vo);
                arrayList.add(vo);
            } catch (Exception e) {
                throw new CustomException("分页对象实例化错误");
            }
        });
        return arrayList;
    }

    /**
     * 判断当前用户是否是超级管理员
     * @return
     */
    public boolean isSuperAdmin() {
        if(EnumUserType.SUPPER_ADMIN.getCode().equals(getUserLoginInfo().getType())) {
            return true;
        }
        return false;
    }


}
